﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Queries.Forecasts.GetOne;

public class GetOneForecastsQueryHandler : IRequestHandler<GetOneForecastsQueryRequest, GetOneForecastsQueryResponse>
{
    private readonly IForecastRepository _forecastRepository;
    private readonly IMapper _mapper;

    public GetOneForecastsQueryHandler(IForecastRepository forecastRepository, IMapper mapper)
    {
        _forecastRepository = forecastRepository;
        _mapper = mapper;
    }

    public async Task<GetOneForecastsQueryResponse> Handle(GetOneForecastsQueryRequest request, CancellationToken cancellationToken)
    {
        var forecast = await _forecastRepository.FirstOrDefaultAsync(x => x.Id == request.ForecastId, cancellationToken);
        if (forecast == null) throw new NotFoundException($"Прогноз погоды с id '{request.ForecastId}' не найден");

        return _mapper.Map<GetOneForecastsQueryResponse>(forecast);
    }
}